/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package axil.stdlib.numbers.type;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.api.error.AxilException;
import axil.framework.type.Mathematical;
import axil.framework.type.UnitizedValue;
import axil.stdlib.core.type.Atom;
import axil.stdlib.core.type.Nil;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import static axil.framework.Functions.*;


/**
 * The generic base type for all numeric objects. Because of the way the
 * numeric tower works you must subclass this and not directly implement the
 * AxilObject interface to define a new numeric type.
 */
public abstract class Num extends Atom implements Mathematical {
	public static final int
		UNITIZED	= 0,
		INT 		= 1,
		BIGINT		= 3,
		FRACTION 	= 5,
		FP 			= 7,
        DECIMAL		= 8,
		PERCENT		= 10,
		MONEY		= 12;


	public static Num convert(Number v) {
        if (v instanceof Integer)		return Int.from((Integer) v);
        if (v instanceof Long)			return BigInt.from((Long) v);
        if (v instanceof BigInteger)	return BigInt.from((BigInteger) v);
        if (v instanceof BigDecimal)	return Decimal.from((BigDecimal) v);
        if (v instanceof Double)		return FloatingPoint.from((Double) v);
        if (v instanceof Float)		    return FloatingPoint.from(((Float) v).doubleValue());
        if (v instanceof Short)		    return Int.from(((Short) v).intValue());
        if (v instanceof Byte)		    return Int.from(((Byte) v).intValue());
        if (v instanceof AtomicInteger) return Int.from(((AtomicInteger) v).intValue());
        if (v instanceof AtomicLong)    return BigInt.from(((AtomicLong) v).longValue());
        throw unreachable();
	}


	/**
	 * Convert the given string into a suitable numeric object, supporting
	 * integer, decimal and fractional values. Percentage values and any
	 * extended literals or unitized types are not supported.
	 */
	public static Num convert(String text) {
		if (text.indexOf('/') > 0) {
			return (Num)Fraction.type.parse(text);
		}
		if (text.indexOf('.') > 0) {
			return Decimal.from(text);
		}
		if (text.length() > 9) {
			return (Num)BigInt.type.parse(text);
		}
		return (Num)Int.type.parse(text);
	}


	/**
	 * Tell if this object is equivalent to the given object. The object given
	 * is never null. The object given may be of any type of value object.
	 * Objects of incompatible types return a false value, not an exception.
	 */
	public boolean equalTo(AxilObject other) {
		if (other instanceof Num) {
			Num o = (Num)other;
			int kind = max(this.kind(), o.kind());
			return this.as(kind).comparedTo(o.as(kind)) == 0;
		}
		return false;
	}


	/**
	 * Tell the magnitude of this numeric value. This is used in all arithmetic
	 * computations to ensure like objects are used.
	 */
	public abstract int kind();


	/**
	 * Tell if this number has any significant fractional digits. For example,
	 * the number 3.1 would return true, but 3.0 would not.
	 */
	public abstract boolean fractional();


	/**
	 * Get this value as an integer value, discarding any fractional component.
	 * For example, 12.65 returns the integer value 12. No rounding is performed,
	 * only truncation. If the value is greater than what can fit in a 64-bit
	 * integer, then an exception is thrown.
	 */
	public abstract long whole();


	/**
	 * Get the fractional portion of this numeric value as a floating point
	 * value. For example, 12.325 returns a value of 0.325. If there is no
	 * fractional portion, then 0.0 is returned.
	 */
	public abstract double tenths();


	/**
	 * Return a floating point representation of this object. It is understood
	 * the some loos of information may result. Invoking this method is
	 * accepting that side effect.
	 */
	public abstract double fp();


	/**
	 * Return a true value if this number is greater than zero. A value of zero
	 * returns a false value.
	 */
	public abstract boolean positive();


	/**
	 * Get the underlying value for this numeric object. For most numbers, they
	 * simply return themselves, but for compound numbers (such as percent and
	 * money) the return the underlying value.
	 */
	public Num number() {
		return this;
	}


	/**
	 * Return the value of this object as an object of the indicated size. It
	 * can be safely assumed that the caller intended whatever side effects
	 * occur as part of the conversion are intentional.
	 */
	public abstract Num as(int kind);


	protected Num num(AxilObject object) {
		if (object instanceof Num) {
			return (Num)object;
		}
		if (object == Nil.object) {
			return Int.zero;
		}
		throw error(axil(), "not-a-number", nv("value", object),
		            nv("type", object.type()));
	}


	/**
	 * Coerce this object into an instance of the given type. If this object
	 * cannot be meaningfully represented as an instance of that type, then an
	 * exception is thrown.
	 *
	 * @param type
	 * 	The type to be coerced to. The object given cannot be null.
	 *
	 * @return
	 * 	Returns an instance of the given type. If this object is nil, then nil
	 * 	is returned.
	 */
	public AxilObject coerce(AxilType type) throws AxilException {
		if (type == type()) {
			return this;
		}
		if (type instanceof Num_Type) {
			return this.as(((Num_Type)type).kind());
		}
		throw error(axil(), "cannot-coerce-object",
		            nv("from", type()), nv("to", type));
	}


	protected int upcast(Num a, Num b) {
		return Math.max(a.kind(), b.kind());
	}


	protected <N> N as(Class<N> type, int kind, AxilObject value) {
		if (value == Nil.object) {
			return as(type, kind, Int.zero);
		}
		if (value instanceof Num) {
			return (N)((Num)value).as(kind);
		}
		throw error(axil(), "not-a-number",
		            nv("value", codify(value)),
		            nv("type", value.type()));
	}


	protected Num mag(Num value) {
		return ((UnitizedValue)value).magnitude();
	}


	/**
	 * Tell if this object, represents a true or false value. In general, true
	 * is returned for any object that is not equivalent to nil, is a number
	 * greater than zero, or is the boolean true value.
	 */
	public boolean bool() {
		return comparedTo(zero()) > 0;
	}


	/**
	 * Transform the given native object into its equivalent value object. The
	 * object given is never null and is guaranteed to be one of the alias types
	 * indicated by this object's type (as reported by the type() method).
	 * If the object is one of the common types, then that indicator is also
	 * given.
	 */
	public AxilObject transform(Object object) {
		return convert((Number) object);
	}


	/**
	 * Return a string representation of this object. The string returned is
	 * never null.
	 */
	public String toString() {
		return this.intrinsic().toString();
	}
}
